package com.example.tx;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;


public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private static Address message = new Address();
    private static List<Address> list = new ArrayList<>();
    private static JsonUtil json = new JsonUtil();
    private static String client_address = null;
    private static int client_potr = 0;

    private static String client_server = null;
    //客户端与服务器端连接成功的时候触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("UDP通道已经连接");

        System.out.println("UDP通道已经连接");
        super.channelActive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet)
            throws Exception {
        // 读取收到的数据

        ByteBuf buf = (ByteBuf) packet.copy().content();
        byte[] req = new byte[buf.readableBytes()];
        InetSocketAddress sender = packet.sender();
        buf.readBytes(req);
        String body = new String(req, CharsetUtil.UTF_8);
        System.out.println("你好"+body);
        Address t = json.fromJson(body, Address.class);//将接收到的json数据进行解析，解析成一个对象

        //客户端判断，判断标识头

        if (t.getSign().contains("q")){
            //将ip地址还有端口，标识头改为Client回复给客户端

            message.setMess(sender.getAddress().toString()+":"+sender.getPort());
            message.setSign("Client");
            //记录一下客户端的ip地址

            list.add(message);

            //记录一下客户端的ip地址和端口，定义在全局

            client_address = sender.getAddress().toString();
            client_potr = sender.getPort();
            System.out.println("ip:"+client_address+"端口:"+client_address);
            // 回复一条信息给客户端

            ctx.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer(json.toJson(list)
                            , CharsetUtil.UTF_8)
                    , packet.sender()));

            //重新定义一个对象把ip地址还有端口传入，标识头改为Server

            Address newInfo = new Address();
            newInfo.setMess(message.getMess());
            newInfo.setSign("Server");

            //给汪汪服务器发送一条消息

            System.out.println("发送的消息为:"+json.toJson(newInfo));
            ctx.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer(json.toJson(newInfo), CharsetUtil.UTF_8),
                    //汪汪服务器地址
                    new InetSocketAddress(
                            "60.205.213.174", 10110
                    )));

        }

        //旺旺接收到我的消息并返回一条消息回来，标识头为Server

        if (t.getSign().contains("Server")){

            Address add = json.fromJson(body, Address.class);
            Address newInfo = new Address();

            //接收到的数据保存，并将标识头设置为True
            newInfo.setMess(add.getMess());
            newInfo.setSign("True");
            System.out.println(json.toJson(newInfo));

            //向我的客户端发送消息，发送旺旺客户端的ip地址和端口

            if (client_address != null){
                ctx.writeAndFlush(new DatagramPacket(

                        Unpooled.copiedBuffer(json.toJson(newInfo), CharsetUtil.UTF_8),
                        //地址

                        new InetSocketAddress(
                                client_address.replace("/",""),client_potr
                        )));
                System.out.println("ip地址："+client_address+"端口号："+client_potr);
            }


//                System.out.println("服务器的ip为:"+client_address.replace("/","")+"端口号:"+client_potr);

        }
        for (int i=0;i<list.size();i++){
            for (int j=list.size()-1;j>i;j--){
                if  (list.get(j).getMess().equals(list.get(i).getMess()))  {
                    list.remove(j);
                }
            }
        }
    }
    //消息没有结束的时候触发
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    //捕获异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        System.out.println("UdpServerHandler exceptionCaught" + cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }
}

